package com.shoponline.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.shoponline.dao.UserDAOTest;
import com.shoponline.po.User;

public class UserDAOHibernate 
	extends GenericHibernateDAO<User,String>
    implements UserDAOTest {

	
	/**
	 * 根据用户编号得到用户实例对象
	 * @param id 用户编号
	 * @param lock boolean表示是否枷锁
	 * @return 返回的用户实例
	 * */
	@Override
	public User findById(String id, boolean lock) {
		
		return super.findById(id, lock);
		
	}

	@Override
	public List<User> findAll() {
		
		Session session = getSession();
		session.beginTransaction();
		//HQL是一种完全面向对象的查询语句
		Query query = session.createQuery("from com.shoponline.po.User");
		ArrayList<User> array= (ArrayList<User>) query.list();
		clear();
		return array;
		
	}

	@Override
	public List<User> findByExample(User exampleInstance) {
		
		return null;
		
	}

	/**
	 * 使entity持久状态
	 * 持久态对象是指与数据库表中得某一条记录相对应，已经获得持久化标志的对象
	 * @param entity 用户对象实例
	 * */
	@Override
	public User makePersistent(User entity) {
		
		Session session = getSession();
		session.beginTransaction();
		session.save(entity);
		session.getTransaction().commit();
		clear();	
		return entity;
	}

	/**
	 * 使entity位瞬态
	 * 瞬时态太对象指由new操作创建的，且尚未与Hibernate Session关联的对象
	 * */
	@Override
	public void makeTransient(User entity) {
		
		Session session = getSession();
		session.beginTransaction();
		session.delete(entity);
		session.getTransaction().commit();
		clear();
		
	}

	@Override
	public User checkLogin(String email, String passwrod) {
		
		Session session = getSession();
		session.beginTransaction();
		Query query = session
				.createQuery("from com.shoponline.po.User user where user.email='"+email+"' and user.password='"+passwrod+"'");
		
		ArrayList<User> arr = (ArrayList<User>) query.list();
		User user = null;
		if(arr.size()>0){
			
			
			user = arr.get(0);
			System.out.println("check success.."+user.getUsername());
		}
		return  user;
		
	}


	
}
